package com.yujin;
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
/**
 * Java对象转化为xml和将xml转化为Java对象工具类
 * @author Administrator
 */
public class XmlUtils {
	
	public static <T> String javaBean2Xml(Class<T> clazz,T t){
		try {
			//创建JAXBContext对象
			JAXBContext context = JAXBContext.newInstance(clazz);
			//创建Marshaller对象,编排(将Java对象转化为xml)
			Marshaller marshaller = context.createMarshaller();
			StringWriter str = new StringWriter();
			marshaller.marshal(t,str);
			return str.toString();
		} catch (JAXBException e) {
			e.printStackTrace();
			return null;
		}
		
	}
	
	public static <T> Object xml2JavaBean(Class<T> clazz,String xml){
		try {
			//创建JAXBContext对象
			JAXBContext context = JAXBContext.newInstance(clazz);
			//创建Marshaller对象,编排(将Java对象转化为xml)
			Unmarshaller unmarshaller = context.createUnmarshaller();
			return unmarshaller.unmarshal(new StringReader(xml));
		} catch (JAXBException e) {
			e.printStackTrace();
			return null;
		}
	}
}
